package lock;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class LockTest {

    public static void main(String[] args) {
        Resource r = new Resource();
        Condition condition = r.lock.newCondition();
        new Thread(new PutTest(r, condition)).start();
        new Thread(new OutputTest(r, condition)).start();
    }
}

//定义共享变量
class Resource {
    public String name;
    public char sex;
    public boolean flag;
    //创建一个Lock对象,共享锁对象
    Lock lock = new ReentrantLock();
}

//创建输入类
class PutTest implements Runnable {

    private Resource r;
    private int x;
    private Condition condition;

    public PutTest(Resource r, Condition condition) {
        this.r = r;
        this.condition = condition;
    }

    @Override
    public void run() {
        while (true) {
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            r.lock.lock();
            try {
                if (!r.flag) {
                    if (x % 2 == 0) {
                        r.name = "马超";
                        r.sex = '男';
                    } else {
                        r.name = "小乔";
                        r.sex = '女';
                    }
                    x++;
                }
                r.flag = true;
                condition.signal();
                try {
                    condition.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            } finally {
                r.lock.unlock();
            }
        }
    }
}

//创建输出类
class OutputTest implements Runnable {
    private Resource r;
    private Condition condition;

    public OutputTest(Resource r, Condition condition) {
        this.r = r;
        this.condition = condition;
    }

    @Override
    public void run() {
        while (true) {
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            r.lock.lock();
            try {
                if (r.flag) {
                    System.out.println(r.name + r.sex);
                }
                r.flag = false;
                condition.signal();
                try {
                    condition.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            } finally {
                r.lock.unlock();
            }
        }
    }
}